package top.datacluster.basic.algorithm.leetcode;

import java.util.List;

public class TwoNumsSumLeetCode2 {




    public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
        ListNode root1 = l1;
        ListNode root2 = l2;
        ListNode resut = new ListNode(0);
        ListNode root = resut;
        int flag = 0;
        while (root1 != null && root2 != null){
            int temp = root1.val + root2.val + flag;
            if (temp >= 10){
                temp = temp % 10;
                flag = 1;
            }else{
                flag = 0;
            }
            ListNode node = new ListNode(temp);
            resut.next = node;
            resut = resut.next;
            root1 = root1.next;
            root2 = root2.next;
        }
        while ( root1 != null){
            int temp = root1.val +  flag;
            if (temp >= 10){
                temp = temp % 10;
                flag = 1;
            }else {
                flag = 0;
            }
            ListNode node = new ListNode(temp);
            resut.next = node;
            resut = resut.next;
            root1 = root1.next;

        }

        while ( root2 != null){
            int temp = root2.val +  flag;
            if (temp >= 10){
                temp = temp % 10;
                flag = 1;
            }else {
                flag = 0;
            }
            ListNode node = new ListNode(temp);
            resut.next = node;
            resut = resut.next;
            root2 = root2.next;

        }
        if (flag == 1){
            ListNode node = new ListNode(flag);
            resut.next = node;
        }
        return root.next;
    }

    public static void main(String[] args) {

    }


    public class ListNode{
        int val;

        ListNode next;

        ListNode(int val) {
            this.val = val;
        }


    }
}
